package com.ruoyi.service;

import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.ruoyi.dto.FileVO;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class FileServiceImpl implements FileService {
    private String localPathDir="http://soom5aw1d.hn-bkt.clouddn.com/"; // 文件存储路径

    @Override
    public FileVO upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();

        // 创建七牛云配置
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2; // 指定分片上传版本

        // 创建上传管理器
        UploadManager uploadManager = new UploadManager(cfg);

        // 生成上传凭证
        String accessKey = "xe63kOkoZA9IwuhWbO1mztSb18mQcQxEgoRBhg9M";
        String secretKey = "MBesZq-VjLQURNs5xLEmVOVbPl0GlbvIAyWA7zrM";
        String bucket = "jia123456";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);

        // 指定文件名（key）
        String key = fileName;

        // 直接使用 MultipartFile 上传
        Response response = uploadManager.put(file.getBytes(), key, upToken);
        // 解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        System.out.println(putRet.key);
        System.out.println(putRet.hash);
        return new FileVO(fileName, localPathDir+fileName);
        // 返回文件信息

    }

    }
